import router from "../../../../apis/routers";

const key = getFilePathStore(import.meta.url)

export const usePhoneCardStore = defineStore(key, {
    state: () => ({
        phoneInputProps: "",
        phoneCodeInputProps: "",
        consolePrefix: '',
        userLoginComponentStore: userUserLoginComponentStore(),

        lastClickTime: 0, // 记录上次点击的时间
        timer: null as ReturnType<typeof setInterval> | null
    }),
    actions: {
        async initStore() {
            await this.userLoginComponentStore.initStore();
            this.phoneInputProps = '';
            this.phoneCodeInputProps = '';
            this.consolePrefix = '得到手机验证码';
        },
        async getPhoneThrowMessage() {
            return getIsNull(this.phoneInputProps) ? (() => {
                throw '请检查您的输入的手机号'
            })() : (() => {
                !/^1\d{10}$/.test(this.phoneInputProps) ? (() => {
                    throw '请检查您的输入的手机号是否符合格式'
                })() : void 0;
            })()
        },
        async getPhoneCodeThrowMessage() {
            return getIsNull(this.phoneCodeInputProps) ? (() => {
                throw '请检查您的输入的验证码是否为空'
            })() : (() => {
                getSomeValue(this.userLoginComponentStore.agreementComponetStore.agree, false)
                    ? (() => { throw '请先同意协议' })()
                    : void 0;
            })();
        },
        async getPhoneCodeSucessfully() {
            const currentTime = new Date().getTime();
            (currentTime - this.lastClickTime >= 6 * 1000) ? (() => {
                this.lastClickTime = currentTime;
            })() : (() => {
                throw '还未到可点击时间，请稍后再试';
            })();
        },
        async getPhoneCode() {
            try {
                await this.getPhoneThrowMessage();
                await this.getPhoneCodeSucessfully().then(async () => {
                    // TODO: api:得到用户手机验证码
                    const data = await getUserLoginForGetPhoneCodeAPI(this.phoneInputProps);
                    console.log("🚀 ~ awaitthis.getPhoneCodeSucessfully ~ data:", data)
                })
            } catch (error) {
                console.log(error);
            }
        },
        async userLogin() {
            try {
                await this.getPhoneThrowMessage();
                await this.getPhoneCodeThrowMessage();
                // TODO: api:用户登录代码实现
                await getUserLoginForPhoneLoginCodeAPI(this.phoneInputProps, this.phoneCodeInputProps).then((data) => {
                    asyncSetCookie('userLoginTooken', { 'token': data }).then((data) => {
                        console.log("🚀 ~ userLogin ~ data:", data);
                        router.push({ name: 'home' });
                    })
                });
            } catch (error) {
                console.log(error);
            }
        },
    },
    persist: {
        key: key,
        storage: sessionStorage
    }
});